﻿#include "protocol.h"
#include "_def.h"
protocol::protocol(QObject *parent) : QObject(parent)
{

}

protocol::~protocol()
{

}

QByteArray protocol::packet(QByteArray array)
{
    uint32_t length = array.length();
    if(length<=0)
        return QByteArray();

    QByteArray result;
    result.append(PROTOCOL_HEAD);//头
    result.append('\0');
    result.append(QString::asprintf("%u",length));//长度
    result.append('\0');
    result.append(array);//内容
    result.append('\0');
    uint32_t crc = GetCRC32(result);

    result.append(QString::asprintf("%02x",crc));//校验
    result.append('\0');
    result.append(PROTOCOL_TAIL);
    result.append('\0');
    return result;
}

protocol_def protocol::unpacket(QByteArray array)
{
    int i=0;
    int step=0;
    char ch = 0;
    protocol_def pro;
    for(i=0;i<array.size();i++)
    {
        switch (step) {
        case 0://头
            ch=array.at(i);
            if(ch=='\0')
                step++;
            pro.head+=ch;
            break;
        case 1://长度
            ch=array.at(i);
            if(ch=='\0')
                step++;
            pro.length+=ch;
            break;
        case 2://内容
            ch=array.at(i);
            if(ch=='\0')
                step++;
            pro.content+=ch;
            break;
        case 3://校验
            ch=array.at(i);
            if(ch=='\0')
                step++;
            pro.crc32+=ch;
            break;
        case 4://尾
            ch=array.at(i);
            if(ch=='\0')
                step++;
            pro.head+=ch;
            break;
        default:
            break;
        }
    }
    return pro;
}

bool protocol::isValid(protocol_def * def)
{
    bool flag=false;
    if(!def)
        return false;
    if(def->head!=PROTOCOL_HEAD||def->tail!=PROTOCOL_TAIL)
        return false;
    int length = def->length.toUInt(&flag,10);
    if(flag==false)
        return false;
    if(length!=def->content.length())
        return false;
    QByteArray res;
    res+=def->head;
    res+="\0";
    res+=def->length;
    res+="\0";
    res+=def->content;
    res+="\0";
    uint32_t crc = GetCRC32(res);
    QString crc32 = QString::asprintf("%02x",crc);
    if(crc32!=def->crc32)
        return false;
    return true;
}
